package com.querie.dao;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import com.google.gson.Gson;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
import com.querie.config.Configuration;

public class ModelDAO {
	MongoClient mongo;
	DB database;
	DBCollection table;
	int indexOfFold = 0;

	public ModelDAO(int indexOfFold) {
		try {
			mongo = new MongoClient("localhost", 27017);

		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		this.indexOfFold = indexOfFold;
		database = mongo.getDB("mffold" + indexOfFold);
		table = database.getCollection("mfmodel");
	}

	public HashMap<String, Double> getFragmentMap(long sessionid) {
		HashMap<String, Double> map = new HashMap<String, Double>();

		BasicDBObject searchQuery = new BasicDBObject();
		searchQuery.put("sessionid", sessionid);

		DBCursor cursor = table.find(searchQuery);

		if (cursor.hasNext()) {
			BasicDBObject obj = (BasicDBObject) cursor.next();
			Gson gson=new Gson(); 
			map=(HashMap<String,Double>) gson.fromJson(obj.getString("fragments"), map.getClass());
		}
		return map;

	}
	
	public HashSet<Long> getTopKFragmentMap(long sessionid) {
		HashMap<String, Double> map = new HashMap<String, Double>();
		HashMap<String, Double> result = new LinkedHashMap<String, Double>();
		
		HashSet<Long> setTopFragments = new HashSet<Long>();
		
		BasicDBObject searchQuery = new BasicDBObject();
		searchQuery.put("sessionid", sessionid);
		int kVal = Configuration.getkValForFragments();
		DBCursor cursor = table.find(searchQuery);

		if (cursor.hasNext()) {
			BasicDBObject obj = (BasicDBObject) cursor.next();
			Gson gson=new Gson(); 
			map=(HashMap<String,Double>) gson.fromJson(obj.getString("fragments"), map.getClass());
		}
		map = com.querie.util.Util.sortByComparator(map, true);
		int index = 1;
		for (String key:map.keySet())
		{
			result.put(key, map.get(key));
			setTopFragments.add(Long.parseLong(key));
			if (index > kVal)
			{
				break;
			}
			index++;
		}
		return setTopFragments;

	}
	public List<Long> getModelSessionIds()
	{
		List<Long> result = new ArrayList<Long>();
		DBCursor cursor = table.find();
		
		
		while(cursor.hasNext())
		{
			BasicDBObject obj = (BasicDBObject) cursor.next();
			result.add(obj.getLong("sessionid"));
		}

		return result;
		
	}

	public static void main(String a[]) {
		new ModelDAO(1).getTopKFragmentMap(21337l);
	}
	

}
